/**
 * Created by houjianhui on 2017/7/18.
 */
'use strict';
// 工具类

(function(pkg, undefined) {
    Date.prototype.YYYY_MM_DD = 'yyyy-MM-dd';
    Date.prototype.YYYY_MM_DD_HH_MM_SS = 'yyyy-MM-dd hh:mm:ss';

    Date.prototype.format = function(formatStr){
        var str = formatStr;
        var Week = ['日','一','二','三','四','五','六'];

        str=str.replace(/yyyy|YYYY/,this.getFullYear());
        str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));
        // 月份在JS里面是从0开始的
        str=str.replace(/MM/,this.getMonth()>=9?(this.getMonth()+1).toString():'0' + (this.getMonth()+1));
        str=str.replace(/M/g,this.getMonth());

        str=str.replace(/w|W/g,Week[this.getDay()]);

        str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());
        str=str.replace(/d|D/g,this.getDate());

        str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());
        str=str.replace(/h|H/g,this.getHours());
        str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());
        str=str.replace(/m/g,this.getMinutes());

        str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());
        str=str.replace(/s|S/g,this.getSeconds());

        return str;
    };

    /**
     * 使用 HTML5 的 History 新 API pushState 来曲线监听 Android 设备的返回按钮
     * @author azrael
     * @date 2013/02/04
     * @version 1.0
     * @example
     * XBack.listen(function(){
		alert('oh! you press the back button');
	});
     */
    var STATE = 'x-back';
    var element;

    var onPopState = function(event){
        event.state === STATE && fire();
    };

    var record = function(state){
        history.pushState(state, null, location.href);
    };

    var fire = function(){
        var event = document.createEvent('Events');
        event.initEvent(STATE, false, false);
        element.dispatchEvent(event);
    };

    var listen = function(listener){
        element.addEventListener(STATE, listener, false);
    };

    ;!function(){
        element = document.createElement('span');
        window.addEventListener('popstate', onPopState);
        this.listen = listen;
        record(STATE);
    }.call(window[pkg] = window[pkg] || {});

})('XBack');

var Tools = {

    /**
     * token key in cookie
     * */
    TOKEN_KEY_IN_COOKIE: 'TOKEN_KEY_IN_COOKIE',
    DRIVER_KEY_IN_COOKIE: 'DRIVER_KEY_IN_COOKIE',

    /**
     * 设置cookie值
     * @param name cookie name
     * @param value cookie value
     * @param hours 时间(小时)
     */
    setCookie: function(name, value, hours) {
        var d = new Date();
        var offset = 8;
        var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
        var nd = utc + (3600000 * offset);
        var exp = new Date(nd);
        exp.setTime(exp.getTime() + hours * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
    },

    /**
     * 获取cookie值
     * @param name cookie名称
     * @returns {null} cookie值
     */
    getCookie: function(name) {
        var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
        if (arr != null)
            return unescape(arr[2]);
        return null;
    },

    /**
     * 设置token到cookie
     * @param token token字符串
     */
    setToken: function(token, isForcibly) {
        if (isForcibly) {
            this.setCookie(this.TOKEN_KEY_IN_COOKIE, token, 24 * 7);
            return;
        }
        var tokenInCookie = this.getToken();
        if (token && (!tokenInCookie || token !== tokenInCookie))
            this.setCookie(this.TOKEN_KEY_IN_COOKIE, token, 24 * 7);
    },

    /**
     * 获取token
     * @returns {*|null} token
     */
    getToken: function() {
        return this.getCookie(this.TOKEN_KEY_IN_COOKIE);
    },

    /**
     * 设置司机信息
     */
    setDriver: function(driver) {
        var driverInCookie = this.getDriver();
        if (driverInCookie.phone != driver.phone && driver.phone) {
            this.setCookie(this.DRIVER_KEY_IN_COOKIE, JSON.stringify(driver), 24 * 7);
        }
    },

    /**
     * 获取司机信息
     */
    getDriver: function() {
        return JSON.parse(this.getCookie(this.DRIVER_KEY_IN_COOKIE) || JSON.stringify({id: '', name: '', phone: ''}));
    },

    /**
     * 获取openid
     */
    getOpenId: function() {
        return openId;
    },

    /**
     * 获取登录之后路由跳转
     */
    getAfterLoginRouter: function() {
        return afterLoginRouter;
    },

    /**
     * 手机号是否合法
     * @param mobileNo 手机号码
     * @returns {boolean} 合法返回true，反之返回false
     */
    isMobileNo: function (mobileNo) {
        var reg = new RegExp('^1\\d{10}$');
        return reg.test(mobileNo);
    },

    /**
     * 车牌号是否合法
     * @param licenseNumner 车牌号
     * @returns {boolean} 合法返回true，反之返回false
     */
    isLicenseNumber: function (licenseNumner) {
        var reg = new RegExp('^[\u4E00-\u9FA5]{1}[A-Za-z]{1}[\\dA-Za-z]{5}$');
        return reg.test(licenseNumner);
    },

    /**
     * 身份证号是否合法
     * @param idno 身份证号
     * @returns {boolean} 合法返回true，反之返回false
     */
    isIdno: function (idno) {
        var reg = new RegExp('^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X|x)$');
        return reg.test(idno);
    },

    /**
     * 检测vin号是否合法
     */
    checkVin: function(vin) {
        var reg = new RegExp('^([123469JKLRSTVWYZ]{1}[a-zA-Z0-9^IiOoQq]{7}([0-9]|[Xx]){1}[1-9A-Y^IiOoQq]{1}[a-zA-Z0-9^IiOoQq]{1}[0-9]{6})$');
        return reg.test(vin);
    },
    /**
     * 判断邮箱是否合法
     * @param email 邮箱
     * @returns {boolean} 合法返回true,反之返回false
     */
    isEmail: function(email) {
        var reg = new RegExp('^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$');
        return reg.test(email);
    },

    /**
     * 判断密码是否正确
     * @param pwd
     * @returns {boolean} 6-14位数字和英文组合返回true,反之返回false
     */
    isPwd: function (pwd) {
        var reg = new RegExp('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,14}$');
        return reg.test(pwd);
    },
    /**
     * 获取地址全名
     * @param addressObj 地址对象
     */
    getAddressFullName: function(addressObj) {
        var fullName = '';
        if (addressObj.provinceName) {
            fullName += addressObj.provinceName + '-';
        } else if (addressObj.provincename) {
            fullName += addressObj.provincename + '-';
        }
        if (addressObj.cityName) {
            fullName += addressObj.cityName;
        } else if (addressObj.cityname) {
            fullName += addressObj.cityname;
        }
        return fullName;
    },

    /**
     * 将数据对象key值转换成全部小写
     * @param object 数据对象
     * @returns {{}} 转换后对象
     */
    toLowerCase4Obj: function(object) {
        var rtnObj = {};
        for (var i in object) {
            rtnObj[i.toLowerCase()] = object[i];
        }
        return rtnObj;
    },

    /**
     * clone 对象
     * @param obj 对象
     * @returns {{}} 被clone对象
     */
    cloneObj: function(obj) {
        var rtnObj = {};
        for (var i in obj) {
            rtnObj[i] = obj[i];
        }
        return rtnObj;
    },

    /**
     *
     * 去除字符串空格
     * @param str 字符串
     * @param is_global 去除全部空格需传参数 'g'
     * @returns string
     *
     */
    trim: function (str, is_global) {
        var result;
        result = str.replace(/(^\s+)|(\s+$)/g, "");
        if (is_global.toLowerCase() == "g") {
            result = result.replace(/\s/g, "");
        }
        return result;
    },

    /**
     * 获取车型信息字符串
     * @param data
     */
    getTruckTypeString: function(data, split) {
        // 数组
        if (data.hasOwnProperty('length')) {
            var vehiclesStr = [];
            angular.forEach(data, function(i) {
                vehiclesStr.push(i.brandName + '-' + i.vehicleName + '-' +  i.amount + '辆');
            });
            return vehiclesStr.join((split || ''));
        }

    },
    // 获取邀请码
    getInvitation: function() {
        return invitation;
    },
    // 获取我的验证码
    getMyInvitation: function() {
        return myInvitation;
    },
    // 设置我的验证码
    // setMyInvitation: function(invitation) {
    //     myInvitation = invitation;
    // },
    /**
     * 常量值
     */
    constant: {
        // 订单
        order: {
            getConfirmStatus: function() {
                return {
                    key: 30,
                    text: '待确认'
                };
            }
        },
        // 支付
        pay: {
            // 未付款
            getUnpaidStatue: function() {
                return 10;
            },
            // 已付定金
            getDepositStatue: function() {
                return 20;
            },
            // 已付全款
            getAllStatue: function() {
                return 30;
            },
            // 已开发票
            getInvoicedStatue: function() {
                return 40;
            },
            // 微信公众号支付类型
            getWeixinPubPayType: function() {
                return 'wx_pub';
            },
            // 支付宝手机网页支付类型
            getAlipayWapPayType: function() {
                return 'alipay_wap';
            },
            // 支付宝支付类型
            getAlipayPayType: function() {
                return 'alipay';
            },
            // 支付列表
            getPayTypeList: function() {
                var that = this;
                return [{
                    code: that.getWeixinPubPayType(),
                    name: '微信',
                    icon: 'weixin-pay-icon'
                }];
            }
        },
        //  性别
        gender: {
            // 获取男性状态值
            getMaleStatue: function() {
                return 'M';
            },
            // 获取女性状态值
            getFemaleStatus: function() {
                return 'F';
            }
        },
        // 用户类型
        userType: {
            getDriver: function () {
                return 10;
            },
            getOwner: function () {
                return 20;
            },
        },
        // 车型
        truck: {
            secondhand: {
                Y: 'Y',
                N: 'N'
            },
            mobile: {
                Y: 'Y',
                N: 'N'
            }
        }
    },
    date: {
        // 将日期值转成date类型
        value2Date: function(value) {
            return new Date(value);
        }
    },
    // 图片加载失败调用方法
    onLoadImgErrorCallback: function(element, targetSrc) {
        element.src = contextPath + targetSrc;
    },
    getContactType: {
        getDriver: function () {
            return 10;
        },
        getDepartPerson: function () {
            return 20;
        },
        getReceiptPerson: function () {
            return 30;
        }
    }
};